#!/bin/bash
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# This file is for execution by the pre-commit framework.
#
set -e

# shellcheck source=scripts/lib-precommit
source "$(dirname "$0")/lib-precommit"

# Filter out all tests/* files.
declare -a FILES

for param in "$@"; do
    if [[ "$param" == tests* ]]; then
        continue
    fi
    # the enterprise/... files are included via symlinks. The doctests do not work reliably
    # when running out of the enterprise directory. So redirect to the symlink location.
    FILES+=("$(readlink -f "$param" | sed -e "s|/enterprise/|/|g;s|/cloud/|/|g;s|/managed/|/|g")")
done

NUM_PARAM=${#FILES[@]}

if [ "$NUM_PARAM" == "0" ]; then
    echo No files to check. >&2
    exit 0
fi

REPO_PATH="$(git rev-parse --show-toplevel)"
UVENV="$REPO_PATH/scripts/run-uvenv"

pushd "$REPO_PATH" >/dev/null

$UVENV python -m pytest --doctest-modules "${FILES[@]}" || (
    EXIT=$?
    if test $EXIT -eq 5 || test $EXIT -eq 4; then
        # This means no tests have been found.
        exit 0
    else
        exit $EXIT
    fi
)
popd >/dev/null
